package com.tanhua.sso.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tanhua.sso.mapper.UserMapper;
import com.tanhua.sso.pojo.User;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;


import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private HuanXinService huanXinService;

    //校验信息
    public Map loginVerification(String phone, String code) {
        String redisKey = "CHECK_CODE_" + phone;
        boolean isNew = false;
        String realCode = redisTemplate.opsForValue().get(redisKey);
        //验证码不为空,再进行比较
        if (StringUtils.isEmpty(realCode))
            return null;
        if (!StringUtils.equals(realCode, code))
            return null;
        //验证码在校验完成后，需要废弃
        redisTemplate.delete(redisKey);
        //判断是否为新用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getMobile, phone);
        User user = userMapper.selectOne(wrapper);
        if (user == null) {
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            userMapper.insert(user);
            isNew = true;
            //注册环信用户
            huanXinService.register(user.getId());
        }
        //todo 校验是否冻结登录
        //根据userId查询用户
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",user.getId());
        User user1= userMapper.selectOne(queryWrapper);
        //判断用户冻结状态
        if (user1.getFreezingRange()==1){
            String redisUserKey="FREEZEUPDATE"+user.getId();
            //判断redis缓存是否存在 不存在修改用户状态为正常
            if (!redisTemplate.hasKey(redisUserKey)){
                UpdateWrapper<User> updateWrapper=new UpdateWrapper<>();
                updateWrapper.set("freezingRange",0).set("freezingTime",0).eq("id",user1.getId());
                userMapper.update(user1,updateWrapper);
            }else {
                System.out.println(redisTemplate.getExpire(redisUserKey));
                return null;
            }
        }

        //生成token和isNew
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("id", user.getId());//id自增,调用insert方法时,自动对user对象的id进行赋值,故新增时可得到id

        // 生成token
        String tooken = Jwts.builder()
                //.setHeader(header)  //header，可省略
                .setClaims(claims) //payload，存放数据的位置，不能放置敏感数据，如：密码等
                .signWith(SignatureAlgorithm.HS256, secret) //设置加密方法和加密盐
                //.setExpiration(new Date(System.currentTimeMillis() + 300000)) //设置过期时间，单位毫秒值
                .setExpiration(new DateTime().plusHours(12).toDate()) //设置过期时间，12小时后过期
                .compact();

        try {
            //发送用户登录成功的消息
            Map<String, Object> msg = new HashMap<>();
            msg.put("userId", user.getId());
            msg.put("date", System.currentTimeMillis());
            msg.put("type", 1);
            this.rocketMQTemplate.convertAndSend("user-sso-operate", msg);
        } catch (MessagingException e) {
            log.error("发送消息失败！", e);
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("token", tooken);
        resultMap.put("isNew", isNew);
        return resultMap;
    }

    //校验token
    public User checkUserByToken(String token) {
        try {
            // 通过token解析数据
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();//{id=2, exp=1605513392}
            User user = new User();
            user.setId(Long.valueOf(body.get("id").toString()));
            //需要返回user对象中的mobile，需要查询数据库获取到mobile数据
            //如果每次都查询数据库，必然会导致性能问题，需要对用户的手机号进行缓存操作
            //数据缓存时，需要设置过期时间，过期时间要与token的时间一致
            //如果用户修改了手机号，需要同步修改redis中的数据

            String redisKey = "TANHUA_USER_MOBILE_" + user.getId();
            if (!redisTemplate.hasKey(redisKey)) {
                //从数据库user表获取该用户手机号,并存入缓存中
                User u = userMapper.selectById(user.getId());
                user.setMobile(u.getMobile());
                long outTime = Long.valueOf(body.get("exp").toString()) * 1000 - System.currentTimeMillis();
                redisTemplate.opsForValue().set(redisKey, u.getMobile(), Duration.ofMillis(outTime));
            }else{
                user.setMobile(redisTemplate.opsForValue().get(redisKey));
            }
            return user;
        } catch (ExpiredJwtException e) {
            log.info("token已经过期");
        } catch (Exception e) {
            log.error("token不合法 token = ", e);
        }
        return null;
    }
}
